package com.lancoo.znbkxx.uis;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;

import com.lancoo.znbkxx.R;
import com.lancoo.znbkxx.base.AppActivityManager;
import com.lancoo.znbkxx.base.AppSettingsBean;
import com.lancoo.znbkxx.beans.UserInfoBean;
import com.lancoo.cpbase.authentication.base.AddressOperater;
import com.lancoo.cpbase.authentication.base.CurrentUser;
import com.lancoo.cpbase.authentication.base.ExitBack;
import com.lancoo.cpbase.authentication.base.LoginBack;
import com.lancoo.cpbase.authentication.base.LoginOperate;
import com.lancoo.cpbase.authentication.base.TokenListener;
import com.lancoo.cpbase.authentication.base.TokenManager;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Create by TangJun on 2019/2/16
 */
public class WelcomeActivity extends AppCompatActivity {
    SharedPreferences sp;
    @BindView(R.id.iv_people)
    ImageView ivPeople;
    @BindView(R.id.iv_halo)
    ImageView ivHalo;
    private LoginOperate operate;
    private Handler mHandler;
    private Boolean IsActivityDestroyed = false;
    private LoginOperate mOperate;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        AppSettingsBean.setIsFirstLaunch(true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        ButterKnife.bind(this);
        //mTvWelcomeMiddleText.setText(reduceTitle());
        float curTranslationY = ivPeople.getTranslationY();
        ObjectAnimator animator = ObjectAnimator.ofFloat(ivPeople, "translationY", curTranslationY, 20,curTranslationY);

        animator.setDuration(3000);
        animator.start();
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(ivHalo, "alpha", 1f, 0f, 1f);
        animator1.setDuration(3000);
        animator1.start();

        operate = new LoginOperate(this);
        TokenManager.getInstance().addTokenListener(tokenListener);
        setLoginSuccessData();
        mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (getApplication().getSharedPreferences("firstEnter",MODE_PRIVATE).getBoolean("isFirst",true)) {
                    startActivity(new Intent().setClass(WelcomeActivity.this,GuideActivity.class));
                    finish();
                } else {
                    int result = operate.getCurrentUserState();
                    if (result == 2) {
                        translate(result);
                    } else {
                        translate(result);
                    }
                }
            }
        }, 1 * 1000);
        if (!AppSettingsBean.isFirstLaunch()) {
            finish();
            return;
        }
        AppActivityManager.getInstance().addActivity(this);
    }
    public Boolean IsActivityDestroied() {
        return IsActivityDestroyed;
    }
    private TokenListener tokenListener = new TokenListener() {
        @Override
        public void tokenInvalid(int flag) {
            if (IsActivityDestroied()) {
                return;
            }
            if (flag == 0) {// 用户失效
                runOnUiThread(new Runnable() {
                    public void run() {
                        mOperate.openLoginDialog(new LoginBack() {
                            @Override
                            public void loginSuccess() {// 登录成功
                                setLoginSuccessData();
                            }
                        }, true, false, new ExitBack() {
                            @Override
                            public void exit() {
                               AppActivityManager.getInstance().finishAllActivity();
                            }
                        });
                    }
                });
            } else if (flag == 1) {// 其他应用退出导致失效
                //当其他app进行登录操作时将回调tokenInvalid方法，且flag值为1
                runOnUiThread(new Runnable() {
                    public void run() {
                        //强烈建议在此处做整个app的退出操作。
                        AppActivityManager.getInstance().finishAllActivity();; //移除所有activity的方法
                    }
                });
            }
        }
    };
    private void setLoginSuccessData() {
//        UserInfoBean userInfoBean = new UserInfoBean();
        AddressOperater mAddress = new AddressOperater(this);
        String address = mAddress.getBaseAddress();

        UserInfoBean.GlobalGrade = CurrentUser.GlobalGrade;
        UserInfoBean.StuId = CurrentUser.UserID;
        Log.e("setLoginSuccessData","====setLoginSuccessData========StuId=============="+UserInfoBean.StuId);
        UserInfoBean.UserName = CurrentUser.UserName;
        UserInfoBean.GroupName = CurrentUser.GroupName;
        UserInfoBean.GroupID = CurrentUser.GroupID;

        UserInfoBean.UserType = CurrentUser.UserType;
        UserInfoBean.SchoolID = CurrentUser.SchoolID;
        UserInfoBean.Token = CurrentUser.Token;
        Log.e("setLoginSuccessData","=====setLoginSuccessData=======Token============="+UserInfoBean.Token);
        UserInfoBean.PhotoPath = CurrentUser.PhotoPath;
        UserInfoBean.BaseAdress = address;

//        String schoolId = CurrentUser.SchoolID + "";
        /*String schoolCode = "";
        if (schoolId.contains("-")) {
            String[] schoolCodes = schoolId.split("-",3);
            if(schoolCodes.length>=2) {
                schoolCode = schoolCodes[1];
            }
        }*/
      /*  AppSettings settings = AppContext.getInstance().getPersistentDataCenter().getAppSettings();
        AppSettingsBean settingsBean = settings.getSettings();
        settingsBean.setSchoolCode( schoolCode+ "");

        //先清除
        settings.saveSettings(null);
        settings.saveSettings(settingsBean);
        AppContext.getInstance().IpReFresh();

        AppContext.getInstance().getPersistentDataCenter().getUserInfo().saveUserInfo(userInfoBean);

        Logger.e(tag, "userInfoBean:" + userInfoBean.toString());
        ExceptionLogger.log(tag, "userInfoBean:" + userInfoBean.toString());*/
    }

    private SpannableString reduceTitle() {
        String middle = getResources().getString(R.string.welcome_middle_text);
        String bottom = getResources().getString(R.string.welcome_bottom_text);
        SpannableString ss = new SpannableString(middle + "\n\t\t\t" + bottom);
        if (Build.VERSION.SDK_INT >= 23) {
            ss.setSpan(
                    new ForegroundColorSpan(getResources().getColor(
                            R.color.color_434343, null)), 0, middle.length(),
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            ss.setSpan(
                    new ForegroundColorSpan(getResources().getColor(
                            R.color.color_3F3F3F, null)), middle.length() + 4,
                    ss.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        } else {
            ss.setSpan(
                    new ForegroundColorSpan(getResources().getColor(
                            R.color.color_434343)), 0, middle.length(),
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            ss.setSpan(
                    new ForegroundColorSpan(getResources().getColor(
                            R.color.color_3F3F3F)), middle.length() + 4,
                    ss.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }
        return ss;
    }
    /**
     * 0—用户信息不存在，1—用户信息存在且与网络联通，2—用户信息存在但网络错误,4- 存在服务器地址不存在用户信息
     *
     * @param result
     */
    private void translate(int result) {
        switch (result) {
            case 1:
                onLoginSuccessDo(false);
                finish();
                break;
            default:
                goToLoginWidthIdentityJudgment(true);
                break;
        }
    }
    /**
     * 判断用户身份权限
     * @param nessaryDo
     */
    public void goToLoginWidthIdentityJudgment(final boolean nessaryDo) {
        new LoginOperate(this).goToLoginActivity(this,
                new LoginBack() {
                    @Override
                    public void loginSuccess() {
                        onLoginSuccessDo(nessaryDo);
                    }
                }, new ExitBack() {
                    @Override
                    public void exit() {
                        AppActivityManager.getInstance().exit();
                    }
                }, false);
    }

    /**
     * 登录成功的操作
     * @param nessaryDo
     */
    private void onLoginSuccessDo(boolean nessaryDo) {
        AddressOperater addressOperater = new AddressOperater(WelcomeActivity.this);
        String nowAddress = addressOperater.getBaseAddress();
//        if (CurrentUser.UserType == 0) {
//            gotoNormalEnter();
//        } else {
//            // gotoNonaClass();
//        }
        gotoNormalEnter();

    }
    /**
     * 直接进入主页
     */
    private void gotoNormalEnter() {
        sp = getApplication().getSharedPreferences("firstEnter",MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("isFirst",false);
        editor.commit();
        Intent intent = new Intent();
        intent.setClass(WelcomeActivity.this, PhoneMainActivity.class);
        startActivity(intent);
        // }
        finish();
    }
}

